package com.ultrapower.ctool.xn_app;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ultrapower.ctool.ConfUtils;
import com.ultrapower.ctool.bean.UserVo;
import com.ultrapower.ctool.bean.WangGeBean;
import com.ultrapower.ctool.core.CustomApplication;
import com.ultrapower.ctool.core.WGSJAdater;
import com.ultrapower.ctool.http.BaseActivity;
import com.ultrapower.ctool.model.RegisterRolePirVO;
import com.ultrapower.ctool.utils.WGSJDBHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AddWgXXActivity extends BaseActivity implements View.OnClickListener {
    private AutoCompleteTextView fid_add_wgxx;//社区(村)名称
    private EditText address_add_wgxx;//地址
    private EditText lon_add_wgxx;//经度
    private EditText lat_add_wgxx;//纬度
    private EditText introduce_add_wgxx;//网格介绍
    private EditText person_add_wgxx;//负责人姓名
    private EditText persontel_add_wgxx;//负责人电话
    private Spinner status_add_wgxx;//状态
    private TextView save_wgxx;//保存
    private TextView cancle_wgxx;//取消
    private AddWgXXActivity addWgXXActivity = this;
    private ImageView lon_add_wgxx_img;
    private ImageView lat_add_wgxx_img;
    private ArrayAdapter<RegisterRolePirVO> statusAdapter;

    private Gson gson = new Gson();
    public List<UserVo> suggest;
    public ArrayAdapter<UserVo> aAdapter;
    private static final List<RegisterRolePirVO> statuses = new ArrayList<RegisterRolePirVO>();
    private CustomApplication application;
    public LocationClient mLocationClient;
    private AdapterView.OnItemSelectedListener OnCatSpinnerCL = new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            ((TextView) parent.getChildAt(0)).setTextColor(Color.BLACK);
            ((TextView) parent.getChildAt(0)).setTextSize(18);
        }

        public void onNothingSelected(AdapterView<?> parent) {

        }
    };
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Toast.makeText(getApplicationContext(), "网格添加成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(AddWgXXActivity.this, WangGeXXActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                case 0:
                    Toast.makeText(getApplicationContext(), "系统出现异常", Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    Toast.makeText(getApplicationContext(), "资料不能为空", Toast.LENGTH_SHORT).show();
                    break;


            }
        }
    };

    static {
        statuses.add(new RegisterRolePirVO("", ""));
        statuses.add(new RegisterRolePirVO("1", "正常"));
        statuses.add(new RegisterRolePirVO("2", "停用"));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_wg_xx);
        init();
        //wgAdater = new WGSJAdater(this, R.layout.simple_dropdown_item_1line, null, "cn", android.R.id.text1);
        ///fid_add_wgxx.setThreshold(1);
        ///fid_add_wgxx.setAdapter(wgAdater);
        getLocation();
        fid_add_wgxx.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable editable) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String newText = s.toString();
                new AddWgXXActivity.getJson().execute(newText);
            }
        });
    }

    protected void getLocation() {
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(new AddWgXXActivity.MyLocationListener());
        List<String> permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(AddWgXXActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (ContextCompat.checkSelfPermission(AddWgXXActivity.this, android.Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(android.Manifest.permission.READ_PHONE_STATE);
        }
        if (ContextCompat.checkSelfPermission(AddWgXXActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (!permissionList.isEmpty()) {
            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(AddWgXXActivity.this, permissions, 1);
        } else {
            requestLocation();
        }
    }

    private void requestLocation() {
        initLocation();
        mLocationClient.start();
    }

    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
//        int span = 1000;
//        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
//        option.setOpenGps(false);//可选，默认false,设置是否使用gps
//        option.setLocationNotify(false);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
//        option.setIsNeedLocationPoiList(false);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
//        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
//        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0) {
                    for (int result : grantResults) {
                        if (result != PackageManager.PERMISSION_GRANTED) {
                            Toast.makeText(this, "无定位权限", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                    requestLocation();
                } else {
                    Toast.makeText(this, "发生未知错误", Toast.LENGTH_SHORT).show();
                    return;
                }
            default:
        }
    }

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(final BDLocation bdLocation) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("经度:" + bdLocation.getLongitude() + ",纬度:" + bdLocation.getLatitude());
                    lon_add_wgxx.setText(bdLocation.getLongitude() + "");
                    lat_add_wgxx.setText(bdLocation.getLatitude() + "");
                }
            });
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }
    }

    protected void init() {
        fid_add_wgxx = (AutoCompleteTextView) findViewById(R.id.fid_add_wgxx);
        address_add_wgxx = (EditText) findViewById(R.id.address_add_wgxx);
        lon_add_wgxx = (EditText) findViewById(R.id.lon_add_wgxx);
        lat_add_wgxx = (EditText) findViewById(R.id.lat_add_wgxx);
        introduce_add_wgxx = (EditText) findViewById(R.id.introduce_add_wgxx);
        person_add_wgxx = (EditText) findViewById(R.id.person_add_wgxx);
        persontel_add_wgxx = (EditText) findViewById(R.id.persontel_add_wgxx);
        status_add_wgxx = (Spinner) findViewById(R.id.status_add_wgxx);
        save_wgxx = (TextView) findViewById(R.id.save_wgxx);
        cancle_wgxx = (TextView) findViewById(R.id.cancle_wgxx);
        lon_add_wgxx_img = (ImageView) findViewById(R.id.lon_add_wgxx_img);
        lat_add_wgxx_img = (ImageView) findViewById(R.id.lat_add_wgxx_img);
        save_wgxx.setOnClickListener(this);
        cancle_wgxx.setOnClickListener(this);
        lon_add_wgxx_img.setOnClickListener(this);
        lat_add_wgxx_img.setOnClickListener(this);
        application = (CustomApplication) getApplication();

        //将可选内容与ArrayAdapter连接起来
        statusAdapter = new ArrayAdapter<RegisterRolePirVO>(this, android.R.layout.simple_spinner_item, statuses);
        //设置下拉列表的风格
        statusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //将adapter 添加到spinner中
        status_add_wgxx.setAdapter(statusAdapter);
        suggest = new ArrayList<UserVo>();
        fid_add_wgxx.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable editable) {

            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String newText = s.toString();
                new AddWgXXActivity.getJson().execute(newText);
            }

        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lon_add_wgxx_img:
                if (mLocationClient != null) {
                    mLocationClient.stop();
                }
                mLocationClient = new LocationClient(getApplicationContext());
                mLocationClient.registerLocationListener(new BDLocationListener() {
                    @Override
                    public void onReceiveLocation(BDLocation bdLocation) {
                        if (bdLocation == null) {
                            System.out.println("back");
                            return;
                        }
                        System.out.println("经度:" + bdLocation.getLongitude());
                        lon_add_wgxx.setText(bdLocation.getLongitude() + "");
                    }

                    @Override
                    public void onConnectHotSpotMessage(String s, int i) {

                    }
                });
                initLocation();
                mLocationClient.start();
                break;
            case R.id.lat_add_wgxx_img:
                if (mLocationClient != null) {
                    mLocationClient.stop();
                }
                mLocationClient = new LocationClient(getApplicationContext());
                mLocationClient.registerLocationListener(new BDLocationListener() {
                    @Override
                    public void onReceiveLocation(BDLocation bdLocation) {
                        if (bdLocation == null) {
                            System.out.println("back");
                            return;
                        }
                        System.out.println("纬度:" + bdLocation.getLatitude());
                        lat_add_wgxx.setText(bdLocation.getLatitude() + "");
                    }

                    @Override
                    public void onConnectHotSpotMessage(String s, int i) {

                    }
                });
                initLocation();
                mLocationClient.start();
                break;
            case R.id.save_wgxx:
                System.out.println("save");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //startManagingCursor();
                        String districtValue = fid_add_wgxx.getText().toString().trim();
                        //final String _id = new WGSJDBHelper(addWgXXActivity).queryBycn(districtValue);
                        if (//"".equals(((RegisterRolePirVO) status_add_wgxx.getSelectedItem()).getId())
                            //  ||
                                "".equals(address_add_wgxx.getText().toString().trim())
                                        // || suggest.size()<1
                                        || "".equals(lat_add_wgxx.getText().toString().trim())
                                        || "".equals(introduce_add_wgxx.getText().toString().trim())
                                        || "".equals(person_add_wgxx.getText().toString().trim())
                                        || "".equals(persontel_add_wgxx.getText().toString().trim())
                                ) {
                            Message message = new Message();
                            message.what = 2;
                            handler.sendMessage(message);
                        } else {
                            final Map<String, String> map = new HashMap<String, String>();
                            WangGeBean bean = new WangGeBean();
                            map.put("fid", suggest.get(0).getXid());

                            map.put("status", ((RegisterRolePirVO) status_add_wgxx.getSelectedItem()).getId());
                            map.put("address", address_add_wgxx.getText().toString().trim());
                            map.put("lon", lon_add_wgxx.getText().toString().trim());
                            map.put("lat", lat_add_wgxx.getText().toString().trim());
                            map.put("introduce", introduce_add_wgxx.getText().toString().trim());
                            map.put("person", person_add_wgxx.getText().toString().trim());
                            map.put("persontel", persontel_add_wgxx.getText().toString().trim());
                            //map.put("person", person_add_wgxx.getText().toString().trim());
                            Response enttyperesponse = null;
                            try {
                                OkHttpClient client = new OkHttpClient();
                                FormBody.Builder builder = new FormBody.Builder()
                                        .add("userId", String.valueOf(application.getLoginUser().getLogin_id()));
                                for (Map.Entry<String, String> m : map.entrySet()) {
                                    builder.add(m.getKey(), m.getValue());
                                }
                                RequestBody resultRequestBody = builder.build();
                                Request enttypeRequest = new Request.Builder().url(ConfUtils.SERVICE_URL + "app_grid/insertGridInfo").post(resultRequestBody).build();
                                enttyperesponse = client.newCall(enttypeRequest).execute();
                                if (enttyperesponse.isSuccessful()) {
                                    String result = enttyperesponse.body().string();
                                    Map<String, Object> resultMap = gson.fromJson(result, Map.class);
                                    System.out.println(resultMap);
                                    if ((boolean) resultMap.get("success")) {

                                        Message message = new Message();
                                        message.what = 1;
                                        handler.sendMessage(message);


                                    } else {
                                        Message message = new Message();
                                        message.what = 0;
                                        handler.sendMessage(message);
                                    }
                                }
                            } catch (Exception e) {
                                Message message = new Message();
                                message.what = 0;
                                handler.sendMessage(message);
                                e.printStackTrace();
                            } finally {
                                if (enttyperesponse != null) enttyperesponse.close();
                            }
                        }

                    }
                }).start();
                break;
            case R.id.cancle_wgxx:
                System.out.println("cancle");
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stop();
        }
    }

    class getJson extends AsyncTask<String, String, String> {
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            aAdapter = new ArrayAdapter<UserVo>(getApplicationContext(), R.layout.simple_dropdown_item_1line, suggest);
            fid_add_wgxx.setThreshold(1);
            fid_add_wgxx.setAdapter(aAdapter);
            aAdapter.notifyDataSetChanged();
        }

        @Override
        protected String doInBackground(String... key) {
            suggest.clear();
            Response response = null;
            if (key.length != 0 && !"".equals(key[0])) {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("field", "fid")
                            .add("code", "c_aj_wgxx")
                            .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                            .add("like", key.length == 0 ? "" : key[0])
                            .build();
                    Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "widget/findLikeJson").post(requestBody).build();
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {//成功
                        String result = response.body().string();
                        System.out.println(result);
                        suggest = gson.fromJson(result, new TypeToken<List<UserVo>>() {
                        }.getType());
                        System.out.println(suggest);
                    }
                } catch (Exception e) {
                    Log.w("Error", e.getMessage());
                }
            }
            return null;
        }

    }
}
